package com.sx.pipeline.utils

import android.Manifest
import android.content.Context
import android.content.DialogInterface
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.lxj.xpopup.XPopup
import io.rong.imkit.utils.PermissionCheckUtil

/**
 * ```
 * author: Blankj
 * blog  : http://blankj.com
 * time  : 2018/01/06
 * desc  : helper about permission
 * ```
 */
object PermissionHelper {

    fun request(
        context: Context, callback: PermissionUtils.SimpleCallback,
        @PermissionConstants.PermissionGroup vararg permissions: String,
    ) {
        PermissionUtils.permission(*permissions)
            .rationale { activity, shouldRequest -> showRationaleDialog(shouldRequest) }
            .callback(object : PermissionUtils.SingleCallback {
                override fun callback(
                    isAllGranted: Boolean, granted: MutableList<String>,
                    deniedForever: MutableList<String>, denied: MutableList<String>,
                ) {
                    LogUtils.d(isAllGranted, granted, deniedForever, denied)
                    if (isAllGranted) {
                        callback.onGranted()
                        return
                    }
                    if (deniedForever.isNotEmpty()) {
                        showOpenAppSettingDialog()
                        return
                    }
                    val activity = ActivityUtils.getActivityByContext(context)
                    if (activity != null) {
                        SnackbarUtils.with(activity.findViewById(android.R.id.content))
                            .setMessage("Permission denied: ${permissions2String(denied)}")
                            .showError(true)
                    }
                    callback.onDenied()
                }

                fun permissions2String(permissions: MutableList<String>): String {
                    if (permissions.isEmpty()) return "[]"
                    val sb: StringBuilder = StringBuilder()
                    for (permission in permissions) {
                        sb.append(", " + permission.substring(permission.lastIndexOf('.') + 1))
                    }
                    return "[${sb.substring(2)}]"
                }
            })
            .request()
    }

    fun showRationaleDialog(shouldRequest: PermissionUtils.OnRationaleListener.ShouldRequest) {
        shouldRequest.again(true)
    }


    fun showOpenAppSettingDialog() {
        PermissionUtils.launchAppDetailsSettings()
    }

    fun requestTip(
        context: Context,content: String, callback: PermissionUtils.SimpleCallback,
        vararg permissions: String,
    ) {
        if (!PermissionUtils.isGranted(*permissions)) {
            XPopup.Builder(context)
                .asConfirm("授权提示",content,"拒绝","授权",{
                    PermissionUtils.permission(*permissions)
                        .rationale { activity, shouldRequest -> showRationaleDialog(shouldRequest) }
                        .callback(object : PermissionUtils.SingleCallback {
                            override fun callback(
                                isAllGranted: Boolean, granted: MutableList<String>,
                                deniedForever: MutableList<String>, denied: MutableList<String>,
                            ) {
                                LogUtils.d(isAllGranted, granted, deniedForever, denied)
                                if (isAllGranted) {
                                    callback.onGranted()
                                    return
                                }
                                if (deniedForever.isNotEmpty()) {
                                    showOpenAppSettingDialog()
                                    return
                                }
                                val activity = ActivityUtils.getActivityByContext(context)
                                if (activity != null) {
                                    SnackbarUtils.with(activity.findViewById(android.R.id.content))
                                        .setMessage("Permission denied: ${permissions2String(denied)}")
                                        .showError(true)
                                }
                                callback.onDenied()
                            }

                            fun permissions2String(permissions: MutableList<String>): String {
                                if (permissions.isEmpty()) return "[]"
                                val sb: StringBuilder = StringBuilder()
                                for (permission in permissions) {
                                    sb.append(", " + permission.substring(permission.lastIndexOf('.') + 1))
                                }
                                return "[${sb.substring(2)}]"
                            }
                        }).request()
                },null,false).show()
        }else{
            callback.onGranted()
        }

    }

    fun registerRImPermissionFilter(){
        PermissionCheckUtil.setRequestPermissionListListener { activity, permissionsNotGranted, callback ->
            val permissionList = permissionsNotGranted.joinToString(",")
            //录音功能
            val recordPermission = permissionList.contains(Manifest.permission.RECORD_AUDIO)
            //定位功能
            val phonePermission = permissionList.contains(Manifest.permission.READ_PHONE_STATE)
            val locationPermission = permissionList.contains(Manifest.permission.ACCESS_FINE_LOCATION)
            //相册功能
            val readPermission = permissionList.contains(Manifest.permission.READ_EXTERNAL_STORAGE)
            var contentStr =""
            if(recordPermission){
                contentStr="社交聊天使用对话功能需要授权录音。"
            }else if(locationPermission){
                contentStr="发送位置需要授权定位权限和授权读取应用手机信息。"
            }else if(readPermission){
                contentStr="浏览相册需要授权读取内部存储。"
            }
            XPopup.Builder( ActivityUtils.getTopActivity())
                .asConfirm("授权提示",contentStr,"拒绝","授权",{
                    callback.confirmed()
                },{
                    callback.cancelled()
                },false).show()
        }
    }
}

